﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using exsportance.Silverlight.Common.Utils;
using System.Text.RegularExpressions;

namespace exsportance.Silverlight.Validate.Validators
{
    /// <summary>
    /// Validator that returns true if and only if value contains only alphabetic characters
    /// </summary>
    public class AlphaValidator : BaseValidator
    {
        #region members
        /// <summary>
        /// Validation failure message key for when the value contains non-alphabetic
        /// </summary>
        private const string NOT_ALNUM = "notAlnum";

        /// <summary>
        /// Validation failure message key for when the value is an empty string
        /// </summary>
        private const string STRING_EMPTY = "stringEmpty";

        protected Dictionary<string, string> _messagesTemplates = new Dictionary<string, string>(){
        {AlphaValidator.NOT_ALNUM,"'%value%' has not only alphabetic characters"},
        {AlphaValidator.STRING_EMPTY,"'%value%' is an empty string"},
        };

        #endregion

        #region properties
        public bool AllowWhiteSpaces { get; set; }
        #endregion

        #region constructor
        public AlphaValidator(bool allowWhiteSpaces)
            : base()
        {
            AllowWhiteSpaces = allowWhiteSpaces;
        }
        #endregion

        #region protected methods
        /// <summary>
        /// Returns true if and only if value contains only alphabetic characters
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override bool CheckValid(object value)
        {
            string valueString = value as string;

            rememberValue(valueString);

            if (valueString.IsNullOrEmpty())
            {
                raiseMessage(AlphaValidator.STRING_EMPTY);
                return false;
            }

            string whiteSpacePattern = AllowWhiteSpaces ? @"\s" : "";

            //string pattern = @"[^a-zA-Z" + whiteSpacePattern + "]";
            // unicode
            string pattern = @"[^\p{L}" + whiteSpacePattern + "]";

            if (Regex.IsMatch(valueString, pattern, RegexOptions.IgnoreCase))
            {
                raiseMessage(AlphaValidator.NOT_ALNUM);
                return false;
            }

            return true;
        }

        protected override System.Collections.Generic.Dictionary<string, string> getMessageTemplates()
        {
            return _messagesTemplates;
        }
        #endregion
    }
}
